import { useEffect } from 'react';

const PerformanceMonitor = () => {
  useEffect(() => {
    // 监控页面性能
    const observer = new PerformanceObserver((list) => {
      for (const entry of list.getEntries()) {
        if (entry.entryType === 'navigation') {
          console.log('页面加载时间:', entry.loadEventEnd - entry.loadEventStart, 'ms');
        }
        if (entry.entryType === 'paint') {
          console.log(`${entry.name}:`, entry.startTime, 'ms');
        }
      }
    });

    observer.observe({ entryTypes: ['navigation', 'paint'] });

    // 监控LCP (Largest Contentful Paint)
    const lcpObserver = new PerformanceObserver((list) => {
      const entries = list.getEntries();
      const lastEntry = entries[entries.length - 1];
      console.log('LCP:', lastEntry.startTime, 'ms');
    });

    lcpObserver.observe({ entryTypes: ['largest-contentful-paint'] });

    // 监控CLS (Cumulative Layout Shift)
    let clsValue = 0;
    const clsObserver = new PerformanceObserver((list) => {
      for (const entry of list.getEntries()) {
        if (!entry.hadRecentInput) {
          clsValue += entry.value;
        }
      }
      console.log('CLS:', clsValue);
    });

    clsObserver.observe({ entryTypes: ['layout-shift'] });

    return () => {
      observer.disconnect();
      lcpObserver.disconnect();
      clsObserver.disconnect();
    };
  }, []);

  return null; // 这是一个无UI组件
};

export default PerformanceMonitor;
